package com.atguigu.zkcase1;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;

/**
 * className: DistributeServer
 * description:
 * date: 2024/6/21-17:24
 * <p>
 * project: zookeeper
 * package: com.atguigu.zkcase1
 * email: 1085844536@qq.com
 * version:
 *
 * @author WangGuojian
 */
public class DistributeServer {

    /**
     * 注意：逗号前后不能有空格
     */
    private static final String CONNECT_STRING = "192.168.33.100:2181,192.168.33.101:2181,192.168.33.102:2181";
    private static final int SESSION_TIMEOUT = 2000;
    private ZooKeeper zk = null;
    private String parentNode = "/servers";

    /**
     * 创建到 zk 的客户端连接
     */
    public void getConnect() throws IOException {
        zk = new ZooKeeper(CONNECT_STRING, SESSION_TIMEOUT, event -> {
        });
    }

    /**
     * 注册服务器
     *
     * @param hostname 服务器名称
     */
    public void registerServer(String hostname) throws Exception {
        String create = zk.create(parentNode + "/server",
                hostname.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,
                CreateMode.EPHEMERAL_SEQUENTIAL);
        System.out.println(hostname + " is online " + create);
    }

    /**
     * 业务功能
     *
     * @param hostname 服务器名称
     */
    public void business(String hostname) throws Exception {
        System.out.println(hostname + " is working ...");
        Thread.sleep(Long.MAX_VALUE);
    }

    public static void main(String[] args) throws Exception {
        // 1 获取 zk 连接
        DistributeServer server = new DistributeServer();
        server.getConnect();
        // 2 利用 zk 连接注册服务器信息
        server.registerServer(args[0]);
        // 3 启动业务功能
        server.business(args[0]);
    }
}
